<?php
namespace api\modules\v1\controllers;


use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use linslin\yii2\curl;
use api\modules\v1\models\changyue;
use api\modules\v1\models\lianzhuo;
use izyue\admin\models\Area;
use yii\log\Logger;
use api\modules\v1\models\Site;

/*
 * 流量充值平台接口
 * 充值流程
 * 1.接收下游接口POST数据并进行验证。
 * 2.保存数据为订单信息(待充值)。
 * 3.根据接口POST数据筛选平台配置通道。
 * 4.①如果没有对应通道配置,更新订单信息(充值失败),并标注失败原因。
 *   ②如果有对应通道,提交对应上游接口并根据返回数据处理订单。
 *      一、提交成功!——更新订单状态(充值中)。
 *      二、提交失败!——更新订单状态(提交失败)。
 * 5.如果提交成功,等待自动回调或手动回调信息。
 *   ①充值成功!——更新平台订单信息(已完成)。
 *   ②充值失败!——更新平台订单信息(充值失败)。并记录失败原因。
 * 6.返回平台回调接口,平台回调接口处理数据并返回给下游用户。
 *
 * 订单状态 $status  1:待充值; 2:充值中; 3:充值成功; 4:充值失败; 5:提交失败;
 * 接口状态 $code    0:提交成功; -1:参数错误; -2:手机号码无法识别; -3:鉴权错误; -5:网络异常; -6:平台余额不足; -7:系统异常; 
 *                  -8:通道异常;
 * 接口类型:POST;
 * 接口充值参数:@$param = array(
 *              'apikey' => 'qlkhqpttflvas7psj75abbwkwrhgnjg8', //平台用户唯一标示
 *              'sign' => 'abaa4537af7b23e80236ea4bc0e5ed16',//鉴权验证MD5($param['apikey'] . $param['username']);
 *              'phone_no' => '18646546800',//手机号码
 *              'flow_val' => '100',//充值流量
 *              'out_order_id' => 'SH20170118123456', //外部订单号
 *              'timetamp' => '12312312312', //时间戳
 *              'scope' => '0'//0=>国内/1=>省内
 *          );
 */

class SiteController extends Controller
{
    private $mobile_check_url = 'http://tcc.taobao.com/cc/json/mobile_tel_segment.htm';//手机号码验证接口地址

    public function init()
    {
        $this->enableCsrfValidation = false; //取消post csrf验证 否则无法post数据
    }

    public function actionSubmit()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $param = Yii::$app->request->post();
        Yii::getLogger()->log(print_r($param), Logger::LEVEL_ERROR); //默认category为application即应用程序级别的日志
        $checkpost = $this->CheckPost($param, 'submit');
        $param['province'] = $checkpost['province'];
        $param['catName'] = $checkpost['catName'];
        $param['operator'] = $checkpost['operator'];
        $apikeywords = Site::ConfirmApi($param);
        $param['apiid'] = $apikeywords['apiid'];
        Site::SaveOrder($param);
        $model = '\api\modules\v1\models\\' . $apikeywords['keywords'];
        $return = $model::submit($param);
        $return_array = json_decode($return, true);
        $log = array(
            'out_order_id' => $param['out_order_id'],
            'status' => $return_array['code'],
            'return' => $return_array,
            'time' => date('Y-m-d H:i:s', time())
        );
        Yii::getLogger()->log(print_r($log, true), Logger::LEVEL_ERROR); //默认category为application即应用程序级别的日志
        if ($return_array['code'] == '0') {
            Site::UpdateOrderNo($return_array['data']);
        } else {
            $return_array['data']['status'] = 5;
            Site::UpdateOrderStatus($return_array['data']);
            Site::UpdateBlance($param, 1);
        }
        return $return_array;
    }

    //余额查询接口
    public function actionBlance()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $param = Yii::$app->request->post();
        $this->CheckPost($param, 'blance');
        $memberinfo = Site::GetMemberInfoByApikey($param['apikey']);
        $return = array('blance' => $memberinfo['balance']);
        $this->end(0, $return);
    }

    //余额查询接口
    public function actionApiblance()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        //$model = '\api\modules\v1\models\lianzhuo';
        $apis = Site::GetApis();
        $blances = array();
        foreach ($apis as $key => $value)
        {
            $model = '\api\modules\v1\models\\' . $value['keywords'];
            $blances[$value['keywords']] = $model::blance();
        }
       // print_r($blances);exit;
        return $blances;
    }

    //订单查询接口
    public function actionQuery()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $param = Yii::$app->request->post();
        $this->CheckPost($param, 'query');
        $orderinfo = Site::GetOrderInfoByOutOrderId($param['out_order_id']);
        $return = array(
            'order_id' => $orderinfo['ordersn'],
            'out_order_id' => $orderinfo['out_order_id'],
            'phone_no' => $orderinfo['phone_no'],
            'status' => $orderinfo['status'],
            'report_time' => $orderinfo['report_time'],
            'err_desc' => $orderinfo['desc'],
        );
        $this->end(0, $return);
    }

    /*
     * 平台访问上游接口查询订单状态并更新。
     * 此方法需要定时任务
     */
    public function actionApiquery()
    {
        $orders = Site::GetAllOrdersInHours();
        foreach ($orders as $key => $value) {
            $apikeyword = Site::GetApiKeywordsByOutOrderId($value['out_order_id']);
            $model = '\api\modules\v1\models\\' . $apikeyword;
            $param = array('out_order_id' => $value['out_order_id']);
            $return = $model::query($param);
            $return_array = json_decode($return, true);
            $param['status'] = !empty($return_array['code']) ? $return_array['code'] : '2';
            Site::UpdateOrderStatus($param);
            $log = array(
                'out_order_id' => $value['out_order_id'],
                'status' => $return_array['code'],
                'time' => date('Y-m-d H:i:s', time())
            );
            Yii::getLogger()->log(print_r($log, true), Logger::LEVEL_ERROR); //默认category为application即应用程序级别的日志
        }
        return 'ok';
    }

    //回调地址接口
    public function actionBack()
    {
        $orders = Site::GetAllOrdersIsBack();
        foreach ($orders as $key => $value) {
            $backurl = Site::GetBackUrl($value['mid']);
            $param = array(
                'order_id' => $value['ordersn'],
                'out_order_id' => $value['out_order_id'],
                'phone_no' => $value['phone_no'],
                'status' => $value['status'],
                'report_time' => $value['report_time'],
                'err_desc' => $value['desc'],
            );
            Site::curl_http($backurl, $param);
            Yii::getLogger()->log(print_r($param, true), Logger::LEVEL_ERROR); //默认category为application即应用程序级别的日志
        }
        return 'ok';
    }

    //验证post数据
    public function CheckPost($param, $action = '')
    {
        if (empty($param)) {
            $this->end(-1);
        }
        $mobile = array();
        if (empty($action)) {
            $this->end(-7);
        }
        if ($action == 'submit') {
            if (empty($param['apikey']) || empty($param['sign']) || empty($param['phone_no']) ||
                empty($param['flow_val']) || empty($param['out_order_id']) || empty($param['timetamp']) ||
                !isset($param['scope'])
            ) {
                $this->end(-1);
            }
            $mobile = $this->GetMobileArea($param['phone_no']);
            if (empty($mobile['catName']) || empty($mobile['province'])) {
                $this->end(-2);
            }
        } elseif ($action == 'blance') {
            if (empty($param['apikey']) || empty($param['sign'])) {
                $this->end(-1);
            }
        } elseif ($action == 'query') {

            if (empty($param['apikey']) || empty($param['sign']) || empty($param['out_order_id'])) {
                $this->end(-1);
            }
        } elseif ($action == 'back') {

        }
        $this->CheckSign($param);
        return $mobile;
    }

    //验证sign
    public function CheckSign($param)
    {
        $res = Site::GetMemberInfoByApikey($param['apikey']);
        if (empty($res) || MD5($res['apikey'] . $res['username']) != $param['sign']) {
            $this->end(-3);
        }
    }

    //获取手机号码信息（归属地，运营商）
    public function GetMobileArea($mobile)
    {
        //根据淘宝的数据库调用返回值
        $url = $this->mobile_check_url . "?tel=" . $mobile . "&t=" . time();
        $content = file_get_contents($url);
        $html = iconv("gb2312", "utf-8//IGNORE", $content);
        @$data = explode(',', $html);
        @$province = explode(':', $data[1]);
        @$catname = explode(':', $data[2]);
        @$array = array(
            trim(@$province[0]) => str_replace("'", "", @$province[1]),
            trim(@$catname[0]) => str_replace("'", "", @$catname[1])
        );
        if (!empty($array) && isset($array['catName'])) {
            if ($array['catName'] == "中国移动") {
                $array['operator'] = 1;
            } elseif ($array['catName'] == "中国联通") {
                $array['operator'] = 2;
            } elseif ($array['catName'] == "中国电信") {
                $array['operator'] = 3;
            }
        } else {
            $this->end(-2);
        }
        return $array;
    }

    private function queryend($code = 1, $data = array())
    {
        switch ($code) {
            case 1 :
                $message = '待充值';
                break;
            case 2 :
                $message = '充值中';
                break;
            case 3 :
                $message = '充值成功';
                break;
            case 4 :
                $message = '充值失败';
                break;
            case 5 :
                $message = '错误';
                break;
            default :
                $message = '待充值';
                break;
        }
        echo json_encode([
            'code' => $code,
            'message' => $message,
            'data' => $data
        ], JSON_UNESCAPED_UNICODE);
        Yii::$app->end();
    }

    private function end($code = 0, $data = array())
    {
        switch ($code) {
            case 0 :
                $message = '处理成功';
                break;
            case -1 :
                $message = '参数错误';
                break;
            case -2 :
                $message = '手机号码无法识别';
                break;
            case -3 :
                $message = '鉴权错误';
                break;
            case -5 :
                $message = '网络异常';
                break;
            case -6 :
                $message = '平台账户余额不足';
                break;
            case -7 :
                $message = '系统异常';
                break;
            case -8 :
                $message = '通道异常';
                break;
            default :
                $message = '提交成功';
                break;
        }
        echo json_encode([
            'code' => $code,
            'message' => $message,
            'data' => $data
        ], JSON_UNESCAPED_UNICODE);
        Yii::$app->end();
    }
}
